package org.com.gamemall.Utity;

import lombok.extern.slf4j.Slf4j;
import org.com.gamemall.Entity.UserVoucher;
import org.com.gamemall.Entity.Voucher;
import org.com.gamemall.Service.IUserVoucherService;
import org.com.gamemall.Service.IVoucherService;
import org.springframework.amqp.core.ExchangeTypes;
import org.springframework.amqp.rabbit.annotation.Exchange;
import org.springframework.amqp.rabbit.annotation.Queue;
import org.springframework.amqp.rabbit.annotation.QueueBinding;
import org.springframework.amqp.rabbit.annotation.RabbitListener;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Component;

import java.time.LocalDateTime;
import java.util.Map;


@Component
@Slf4j
public class RabbitListenner {
    @Autowired
    private IUserVoucherService userVoucherService;
    @Autowired
    private IVoucherService voucherService;

    @RabbitListener(bindings = @QueueBinding(
            value = @Queue(value = "order.queue", durable = "true"),
            exchange = @Exchange(value = "order.topic", type = ExchangeTypes.TOPIC),
            key = "订单创建成功"
    ))
    public void handleOrderMessage(Map<String, Object> message) {
        log.info("接收到订单消息：{}", message);
        // 这里可以添加订单处理逻辑
        Long userId = (Long) message.get("userId");
        Long voucherId = (Long) message.get("voucherId");

        //创建订单
        UserVoucher uv = new UserVoucher();
        uv.setUserId(userId);
        uv.setVoucherId(voucherId);
        userVoucherService.save(uv);
        log.info("下单成功");
        //数据库执行操作
        boolean update = voucherService.lambdaUpdate().setSql("stock=stock-1")
                .eq(Voucher::getId, voucherId)
                .gt(Voucher::getStock, 0)
                .update();
        if (!update) {
            log.info("库存不足");
        }
        log.info("修改库存成功");

        log.info("处理用户 {} 的订单 {}, voucherId {}", userId, voucherId);
    }
}

